package com.fingard.dsp.bank.directbank.alipay01;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AccountLogItemResult;
import com.alipay.api.request.AlipayDataBillAccountlogQueryRequest;
import com.alipay.api.request.AlipayDataDataserviceBillDownloadurlQueryRequest;
import com.alipay.api.response.AlipayDataBillAccountlogQueryResponse;
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;
import com.fingard.constant.DateFormat2;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.SendBankRespose;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.text.SplitHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.util.ZipUtils;
import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 支付宝历史明细查询
 *
 * 需求：支付宝对账单文件以历史明细形式返回
 * 备注：该接口为个性化接口，目前支持项目：安邦
 */
public class ALIPAY01Transaction extends ALIPAY01Base implements ITransaction {
	@Override
	public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
		String requestType = getBankConfig().getValueAsString("requestType");
		if (getBankConfig().getValueAsBool("useAccountlogQuery")) {
			return qryHisTransAct(p_req7516);
		} else {
			if ("ftp".equals(requestType.toLowerCase())) {
				return qryHisTransByFTP(p_req7516);
			} else {
				return qryHisTransByHttp(p_req7516);
			}
		}
	}

	public RetAtsTrans qryHisTransByFTP(Req7516HisTrans p_req7516) throws Exception {
		RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
		retAts.writeStart();

		String tmpRespCode = "";
		String tmpRespInfo = "";

		try {
			logIsExist();

			ActSetItem actItem = getBankConfig().getActSetItem(p_req7516.actNum, "unifiedorder");
			if (actItem != null) {
				Calendar tmpCalendarFrom = Calendar.getInstance();
				tmpCalendarFrom.setTime(p_req7516.getDateFrom());

				Calendar tmpCalendarTo = Calendar.getInstance();
				tmpCalendarTo.setTime(p_req7516.getDateTo());

				int tmpIntDateFrom = 0;
				int tmpIntDateTo = 0;
				while(tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
					Calendar tmpClndrStepTo = Calendar.getInstance();
					tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
					//判断是否跨月
					if(DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1){
						//跨月则设置为月末
						tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
					} else {
						tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
					}

					// 月内日期段内查询
					int tmpDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
					int tmpDateTo = Integer.parseInt(Format.Date8Format.format(tmpClndrStepTo.getTime()));

					FtpSet ftpSet = bankFront.getFtpSet("unifiedorder");
					WriteBankLogLn2("支付宝统一收单历史明细FTP服务器地址:" + ftpSet.serverIP + ":" + ftpSet.port);
					while(tmpDateFrom <= tmpDateTo) {
						String tmpDownFileName = tmpDateFrom + "_" + actItem.pid;
						WriteBankLogLn2("支付宝统一收单历史明细文件所在服务器路径:" + StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + tmpDownFileName + ".zip");

						String tmplocalFileSavePath = createTempFileDirectory() + File.separator + tmpDownFileName + ".zip";
						WriteBankLogLn2("支付宝统一收单历史明细文件保存本地路径:" + tmplocalFileSavePath);

						FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
						FtpReceiver ftpReceiver = ftpPortClient.downloadFile(tmpDownFileName + ".zip", tmplocalFileSavePath);
						if (ftpReceiver.isCompleted) {
							WriteBankLogLn("文件下载已完成，开始解压...");
							String tmpLocalDepressDir = getTempFileDirectory();
							ZipUtils.unZip(tmplocalFileSavePath, tmpLocalDepressDir, "GBK");
//		                    ZipHelper.unzipFile(tmplocalFileSavePath, tmpLocalDepressDir, "GBK");
							WriteBankLogLn("文件解压已完成.");

							String tmpResultFileName = actItem.pid + "_" + tmpDateFrom + "_TRADE_DETAILS.csv";
							String tmpResultFilePath = tmpLocalDepressDir + File.separator + tmpResultFileName;
							WriteBankLogLn2("支付宝统一收单历史明细文件本机路径:" + tmpResultFilePath);

							String tmpStrRet = FileHelper.readFileText(tmpResultFilePath, "GBK");
							WriteBankLogLn2("解压后文件内容为:\r\n" + tmpStrRet);

							if (StringHelper.hasAnyChar(tmpStrRet)) {
								tmpRespCode = "0";

								tmpStrRet = tmpStrRet.substring(tmpStrRet.indexOf("账务流水号"));
								tmpStrRet = tmpStrRet.substring(0, tmpStrRet.indexOf("#"));

								StringReader strReader = new StringReader(tmpStrRet);
								BufferedReader tmpReader = new BufferedReader(strReader);

								String titleLine = tmpReader.readLine();
								String[] columns = titleLine.split(",");

								while (true) {
									String dataLine = tmpReader.readLine();
									if (dataLine == null) {
										break;
									}

									String[] values = dataLine.split(",");
									if (columns.length == values.length) {
										HashMap<String, String> mapKV = SplitHelper.splitAsValueMap(columns, values);

										String busType = "";
										if (mapKV.containsKey("业务类型")) {
											busType = mapKV.get("业务类型").replace("+", "").replace("-", "").trim();
											if ("收费".equals(busType)) {
												continue;
											}
										}

										RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();

										tmpRetDetail.actNum = p_req7516.actNum;
										tmpRetDetail.actArea = p_req7516.actArea;
										tmpRetDetail.cur = p_req7516.actCur;

										tmpRetDetail.busType = busType;
										if ("提现".equals(busType)) {
											if (mapKV.containsKey("支出金额（-元）")) {
												tmpRetDetail.tranAmt = mapKV.get("支出金额（-元）").replace("+", "").replace("-", "").trim();
											}
											tmpRetDetail.cdFlag = "1";
										} else {
											if (mapKV.containsKey("收入金额（+元）")) {
												tmpRetDetail.tranAmt = mapKV.get("收入金额（+元）").replace("+", "").replace("-", "").trim();
											}
											tmpRetDetail.cdFlag = "2";
										}

										if (mapKV.containsKey("待处理余额（元）")) {
											tmpRetDetail.accBal = mapKV.get("待处理余额（元）").replace("`", "").trim();
										}

										if (mapKV.containsKey("商户订单号")) {
											tmpRetDetail.askNumber = mapKV.get("商户订单号").replace("`", "").trim();
										}
										if (mapKV.containsKey("账务流水号")) {
											tmpRetDetail.actSeqNo = mapKV.get("账务流水号").replace("`", "").trim();
										}
										if (mapKV.containsKey("业务流水号")) {
											tmpRetDetail.bnkSeqNo = mapKV.get("业务流水号").replace("`", "").trim();
										}

										if (mapKV.containsKey("对方账号")) {
											tmpRetDetail.recAccNum = mapKV.get("对方账号").replace("`", "").trim();
										}

										String billDateTime = "";
										if (mapKV.containsKey("发生时间")) {
											billDateTime = mapKV.get("发生时间").replace("`", "").trim();
										}
										Date busDateObj = new DateFormat2("yyyy-MM-dd HH:mm:ss").parse(billDateTime);
										tmpRetDetail.tranDate = Format.Date10Format.format(busDateObj);
										tmpRetDetail.tranTime = Format.DateTimeFormat.format(busDateObj);
										tmpRetDetail.postTimestamp = Format.DateTime14Format.format(busDateObj);
										tmpRetDetail.valueDate = Format.Date10Format.format(busDateObj);

										if (mapKV.containsKey("备注")) {
											tmpRetDetail.comment = mapKV.get("备注").replace("`", "").trim();
										}

										retAts.writeRetDetail(tmpRetDetail);
									} else {
										break;
									}
								}
							} else {
								tmpRespCode = "-1";
								tmpRespInfo = "解压后历史明细结果文件内容为空";
							}
						} else {
							tmpRespCode = "-1";
							tmpRespInfo = "支付宝统一收单历史明细下载失败,原因:\r\n" + ftpReceiver.connMsg;
						}

						tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
						tmpDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
					}

					tmpCalendarFrom = tmpClndrStepTo;
					tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
					tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
					tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
				}
			} else {
				tmpRespCode = "-1";
				tmpRespInfo = "未找到账号[" + p_req7516.actNum + "]商户配置信息!";
			}
		} catch (Exception e) {
			tmpRespCode = "-1";
			tmpRespInfo = e.getMessage();
			WriteBankLogLn(e);
			e.printStackTrace();
		}

		if(retAts.getWrittenRdCount() == 0){
			retAts.writeRespCode("0");
			retAts.writeRespInfo("交易为空");

			if("-1".equals(tmpRespCode)){
				retAts = new RetAtsTrans(p_req7516.reqHeader);
				retAts.writeStart();
				retAts.writeRespCode(tmpRespCode);
				retAts.writeRespInfo(tmpRespInfo);
			}
		}

		retAts.writeEnd();
		return retAts;
	}

	public RetAtsTrans qryHisTransByHttp(Req7516HisTrans p_req7516) throws Exception {
		RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
		retAts.writeStart();

		String tmpRespCode = "";
		String tmpRespInfo = "";

		try {
			logIsExist();

			ActSetItem actItem = getBankConfig().getActSetItem(p_req7516.actNum, "singlePay");
			if (actItem != null) {
				Calendar tmpCalendarFrom = Calendar.getInstance();
				tmpCalendarFrom.setTime(p_req7516.getDateFrom());

				Calendar tmpCalendarTo = Calendar.getInstance();
				tmpCalendarTo.setTime(p_req7516.getDateTo());

				int tmpIntDateFrom = 0;
				int tmpIntDateTo = 0;
				while(tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
					Calendar tmpClndrStepTo = Calendar.getInstance();
					tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
					//判断是否跨月
					if(DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1){
						//跨月则设置为月末
						tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
					} else {
						tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
					}

					// 月内日期段内查询
					int tmpDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
					int tmpDateTo = Integer.parseInt(Format.Date8Format.format(tmpClndrStepTo.getTime()));
					while(tmpDateFrom <= tmpDateTo) {
						AlipayClient alipayClient;
						if (getBankConfig().getValueAsBool("isPublicKeyAndCert")){
							alipayClient = new DefaultAlipayClient(getCertAlipayRequest(actItem));
						} else {
							alipayClient = new DefaultAlipayClient(bankFront.serverURL, actItem.appId,
									actItem.ownKeyStorePath, "json", getCharset(), actItem.oppCertFilePath, "RSA2");
						}


						JSONObject json = new JSONObject();
						String version = getBankConfig().getValueAsString("version").trim();
						String billType = getBankConfig().getValueAsString("bill_type").trim();
						//保险默认使用trade
						if(StringHelper.isNullOrEmpty(version)||"insurance".equals(version)){
							json.put("bill_type","trade");
						}else if("ats".equals(version)) {
							//ats根据配置决定,默认signcustomer
							if(StringHelper.isNullOrEmpty(billType)){
								billType = "signcustomer";
							}
							if (!"trade".equals(billType) && !"signcustomer".equals(billType)) {
								throw new Exception("bill_type标签配置有误");
							}
							json.put("bill_type", billType);

						}else {
							throw new Exception("version标签配置有误");
						}
						json.put("bill_date", Format.Date10Format.format(tmpCalendarFrom.getTime()));

						AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();
						request.setBizContent(JSON.toJSONString(json));

						WriteBankUrlLogLn(bankFront.serverURL);
						WriteBankLogStep2(request.getBizContent());

						AlipayDataDataserviceBillDownloadurlQueryResponse response = null;
                        Boolean useAppAuthToken = getBankConfig().getValueAsBool("useAppAuthToken");
                        Boolean useCertModel = getBankConfig().getValueAsBool("useCertModel");
						if(useAppAuthToken){
							if(StringHelper.isNullOrEmpty(actItem.appAuthToken)){
								throw new Exception("appAuthToken标签配置有误");
							}
							response = alipayClient.execute(request,"",actItem.appAuthToken);
						}else if (useCertModel){
							response = alipayClient.certificateExecute(request);
						} else {
                            response = alipayClient.execute(request);
                        }

						WriteBankLogStep3(response.getBody());


						if ("10000".equals(response.getCode())) {
							String filePath = createTempFileDirectory() + File.separator + p_req7516.actNum + "_" + tmpDateFrom + ".csv.zip";
							WriteBankLogLn2("账单下载后保存到本地路径: " + filePath);

							String billUrl = response.getBillDownloadUrl();
							WriteBankLogLn2("账单地址获取成功,账单地址链接(30秒有效)为:\r\n" + billUrl);

							SendBankRespose tmpBankRet = smsGet(billUrl, filePath);
							WriteBankLogStep3(tmpBankRet);


							if (tmpBankRet.connState.length() == 0) {
								String tmpStrRet = tmpBankRet.retMessage;
								//保险
								if(!version.equals("ats")) {
									tmpStrRet = tmpStrRet.substring(tmpStrRet.indexOf("支付宝交易号"));
									tmpStrRet = tmpStrRet.substring(0, tmpStrRet.indexOf("#"));

									StringReader strReader = new StringReader(tmpStrRet);
									BufferedReader tmpReader = new BufferedReader(strReader);

									String titleLine = tmpReader.readLine();
									String[] columns = titleLine.split(",");

									while (true) {
										String dataLine = tmpReader.readLine();
										if (dataLine == null) {
											break;
										}

										String[] values = dataLine.split(",");
										if (columns.length == values.length) {
											HashMap<String, String> mapKV = SplitHelper.splitAsValueMap(columns, values);
											RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();

											tmpRetDetail.actNum = p_req7516.actNum;
											tmpRetDetail.actArea = p_req7516.actArea;
											tmpRetDetail.cur = p_req7516.actCur;

											tmpRetDetail.cdFlag = "2";// 收款
											tmpRetDetail.busType = "代收";

											tmpRetDetail.tranAmt = Format.DecimalAmtFormat.format(Double.parseDouble(mapKV.get("订单金额（元）").replace("`", "")));

											if (mapKV.containsKey("商户订单号")) {
												tmpRetDetail.askNumber = mapKV.get("商户订单号").replace("`", "");
											}

											if (mapKV.containsKey("服务费（元）")) {
												tmpRetDetail.fee = Format.DecimalAmtFormat.format(Double.parseDouble(mapKV.get("服务费（元）").replace("`", "")));
											}

											String billDateTime = "";
											if (mapKV.containsKey("完成时间")) {
												billDateTime = mapKV.get("完成时间").replace("`", "");
											}
											Date busDateObj = null;
											if(billDateTime.contains("-") && billDateTime.length()==19){
												busDateObj = new DateFormat2("yyyy-MM-dd HH:mm:ss").parse(billDateTime);
											}else {
												busDateObj = new DateFormat2("yyyy/MM/dd HH:mm").parse(billDateTime);
											}
											tmpRetDetail.tranDate = Format.Date10Format.format(busDateObj);
											tmpRetDetail.tranTime = Format.DateTimeFormat.format(busDateObj);
											tmpRetDetail.postTimestamp = Format.DateTime14Format.format(busDateObj);
											tmpRetDetail.valueDate = Format.Date10Format.format(busDateObj);

											if (mapKV.containsKey("备注")) {
												tmpRetDetail.comment = mapKV.get("备注").replace("`", "");
											}

											retAts.writeRetDetail(tmpRetDetail);
										} else {
											break;
										}
									}

								}else if("trade".equals(billType)){

									tmpStrRet = tmpStrRet.substring(tmpStrRet.indexOf("支付宝交易号"));
									tmpStrRet = tmpStrRet.substring(0, tmpStrRet.indexOf("#"));

									StringReader strReader = new StringReader(tmpStrRet);
									BufferedReader tmpReader = new BufferedReader(strReader);

									String titleLine = tmpReader.readLine();
									String[] columns = titleLine.split(",",100);

									while (true) {
										String dataLine = tmpReader.readLine();
										if (dataLine == null) {
											break;
										}

										String[] values = dataLine.split(",",100);
										if (columns.length >= values.length) {
											if(columns.length>values.length){
												String[] tmpValues = new String[columns.length];
												System.arraycopy(values,0,tmpValues,0,values.length);
												values = tmpValues;
											}
											HashMap<String, String> mapKV = SplitHelper.splitAsValueMap(columns, values);
											RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();

											tmpRetDetail.actNum = p_req7516.actNum;
											tmpRetDetail.actArea = p_req7516.actArea;
											tmpRetDetail.cur = p_req7516.actCur;

											//如果订单金额是正数，则为收入，如果金额为负数，则为支出
											String tranAmt = Format.DecimalAmtFormat.format(Double.parseDouble(mapKV.get("订单金额（元）").trim()));
											if(tranAmt.startsWith("-")) {
												tmpRetDetail.tranAmt = tranAmt.replace("-","");
												tmpRetDetail.cdFlag = "1";// 支出
											}else {
												tmpRetDetail.tranAmt = tranAmt;
												tmpRetDetail.cdFlag = "2";// 收款
												tmpRetDetail.busType = "代收";
											}

//											tmpRetDetail.tranAmt = Format.DecimalAmtFormat.format(Double.parseDouble(mapKV.get("订单金额（元）").trim()));

											if (mapKV.containsKey("商户订单号")) {
												tmpRetDetail.askNumber = mapKV.get("商户订单号").trim();
												tmpRetDetail.usage =tmpRetDetail.askNumber;
											}

											if (mapKV.containsKey("商品名称")) {
												tmpRetDetail.goodsName = mapKV.get("商品名称").replace("`", "");
											}

											if(mapKV.containsKey("对方账户")){
												String account= mapKV.get("对方账户").trim();
												int index = account.lastIndexOf("(");
												if(index!=-1) {
													tmpRetDetail.recAccNum = account.substring(index + 1, account.length() - 1);
													tmpRetDetail.recAccName = account.substring(0, index);
												}else{
													tmpRetDetail.recAccNum = account;
												}

											}

											if (mapKV.containsKey("服务费（元）")) {
												tmpRetDetail.fee = Format.DecimalAmtFormat.format(Double.parseDouble(mapKV.get("服务费（元）").trim()));
											}

											String billDateTime = "";
											if (mapKV.containsKey("完成时间")) {
												billDateTime = mapKV.get("完成时间").trim();
											}
											Date busDateObj = Format.DateTimeFormat.parse(billDateTime);
											tmpRetDetail.tranDate = Format.Date10Format.format(busDateObj);
											tmpRetDetail.tranTime = Format.DateTimeFormat.format(busDateObj);
											tmpRetDetail.postTimestamp = Format.DateTime14Format.format(busDateObj);
											tmpRetDetail.valueDate = Format.Date10Format.format(busDateObj);

											if (mapKV.containsKey("备注")) {
												tmpRetDetail.comment = mapKV.get("备注").trim();
											}

											retAts.writeRetDetail(tmpRetDetail);
										} else {
											break;
										}
									}

								}else{
									//账务明细
									//账务流水号,业务流水号,商户订单号,商品名称,发生时间,对方账号,收入金额（+元）,支出金额（-元）,账户余额（元）,交易渠道,业务类型,备注
									tmpStrRet = tmpStrRet.substring(tmpStrRet.indexOf("账务流水号"));
//									tmpStrRet = tmpStrRet.substring(0, tmpStrRet.indexOf("#"));

									StringReader strReader = new StringReader(tmpStrRet);
									BufferedReader tmpReader = new BufferedReader(strReader);

									String titleLine = tmpReader.readLine();
									String[] columns = titleLine.split(",");

									while (true) {
										String dataLine = tmpReader.readLine();
										if (dataLine == null) {
											break;
										}
										//ATSES-23786 支付宝明细解析不全，客户账单明细文件最后一列为空导致解析时出现数据列少了一列，使用String.split(",",-1),这样就可以把最后一个空字符也识别出来,
										String[] values = dataLine.split(",", -1);
										if (columns.length == values.length) {
											if(columns.length>values.length){
												String[] tmpValues = new String[columns.length];
												System.arraycopy(values,0,tmpValues,0,values.length);
												values = tmpValues;
											}
											HashMap<String, String> mapKV = SplitHelper.splitAsValueMap(columns, values);
											RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();

											tmpRetDetail.actNum = p_req7516.actNum;
											tmpRetDetail.actArea = p_req7516.actArea;
											tmpRetDetail.cur = p_req7516.actCur;

											if(!"0.00".equals(mapKV.get("收入金额（+元）")) && StringHelper.hasAnyChar(mapKV.get("收入金额（+元）"))){
												String tranAmt = Format.DecimalAmtFormat.format(Double.parseDouble(mapKV.get("收入金额（+元）").trim()));
												if(tranAmt.startsWith("-")) {
													tmpRetDetail.tranAmt = tranAmt.replace("-","");
													tmpRetDetail.cdFlag = "1";// 支出
												}else {
													tmpRetDetail.tranAmt = tranAmt;
													tmpRetDetail.cdFlag = "2";// 收款
												}
											}else{
												String tranAmt = Format.DecimalAmtFormat.format(Double.parseDouble(mapKV.get("支出金额（-元）").trim()));
												if(tranAmt.startsWith("-")) {
													tmpRetDetail.tranAmt = tranAmt.replace("-","");
													tmpRetDetail.cdFlag = "1";// 支出
												}else {
													tmpRetDetail.tranAmt = tranAmt;
													tmpRetDetail.cdFlag = "2";// 收入
												}

											}
											tmpRetDetail.accBal = Format.DecimalAmtFormat.format(Double.parseDouble(mapKV.get("账户余额（元）").trim()));

											if(mapKV.containsKey("业务类型")){
												tmpRetDetail.busType = mapKV.get("业务类型").trim();
											}
											if (mapKV.containsKey("商户订单号")) {
												tmpRetDetail.askNumber = mapKV.get("商户订单号").trim();
												tmpRetDetail.usage =tmpRetDetail.askNumber;
											}
											if (mapKV.containsKey("账务流水号")) {
												tmpRetDetail.actSeqNo = mapKV.get("账务流水号").trim();

											}
											if (mapKV.containsKey("业务流水号")) {
												tmpRetDetail.bnkSeqNo = mapKV.get("业务流水号").trim();

											}
											if(mapKV.containsKey("对方账号")){
												String account= mapKV.get("对方账号").trim();
												int index = account.lastIndexOf("(");
												if(index!=-1) {
													tmpRetDetail.recAccNum = account.substring(index + 1, account.length() - 1);
													tmpRetDetail.recAccName = account.substring(0, index);
												}else{
													tmpRetDetail.recAccNum = account;
												}

											}
											String billDateTime = "";
											if (mapKV.containsKey("发生时间")) {
												billDateTime = mapKV.get("发生时间").trim();
											}
											Date busDateObj = Format.DateTimeFormat.parse(billDateTime);
											tmpRetDetail.tranDate = Format.Date10Format.format(busDateObj);
											tmpRetDetail.tranTime = Format.DateTimeFormat.format(busDateObj);
											tmpRetDetail.postTimestamp = Format.DateTime14Format.format(busDateObj);
											tmpRetDetail.valueDate = Format.Date10Format.format(busDateObj);

											if (mapKV.containsKey("备注")) {
												tmpRetDetail.comment = mapKV.get("备注").trim();
											}

											retAts.writeRetDetail(tmpRetDetail);
										} else {
											break;
										}
									}

								}
							} else {
								tmpRespCode = "-1";
								tmpRespInfo = tmpBankRet.retMessage;
							}
						}else if("40004".equals(response.getCode())){
//                      当天没有交易
						}else {
							tmpRespCode = "-1";
							tmpRespInfo = response.getSubMsg();
						}
						tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
						tmpDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
					}

					tmpCalendarFrom = tmpClndrStepTo;
					tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
					tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
					tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
				}
			} else {
				tmpRespCode = "-1";
				tmpRespInfo = "未找到账号[" + p_req7516.actNum + "]商户配置信息!";
			}
		} catch (Exception e) {
			tmpRespCode = "-1";
			tmpRespInfo = e.getMessage();
			WriteBankLogLn(e);
			e.printStackTrace();
		}
		if(tmpRespCode.equals("-1")){
			retAts = new RetAtsTrans(p_req7516.reqHeader);
			retAts.writeStart();//写返回ATS的统一头部信息
			retAts.writeRespCode(tmpRespCode);
			retAts.writeRespInfo(tmpRespInfo);
		}
		else if(retAts.getWrittenRdCount() == 0){
			retAts.writeRespCode("0");
			retAts.writeRespInfo("交易为空");
		}
		retAts.writeEnd();
		return retAts;
	}

	public RetAtsTrans qryHisTransAct(Req7516HisTrans p_req7516) throws Exception {
		RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
		retAts.writeStart();

		String tmpRespCode = "";
		String tmpRespInfo = "";

		try {
			logIsExist();

			ActSetItem actItem = getBankConfig().getActSetItem(p_req7516.actNum, "singlePay");
			if (actItem != null) {
				Calendar tmpCalendarFrom = Calendar.getInstance();
				tmpCalendarFrom.setTime(p_req7516.getDateFrom());

				Calendar tmpCalendarTo = Calendar.getInstance();
				tmpCalendarTo.setTime(p_req7516.getDateTo());

				int tmpIntDateFrom = 0;
				int tmpIntDateTo = 0;
				while(tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
					Calendar tmpClndrStepTo = Calendar.getInstance();
					tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
					//判断是否跨月
					if(DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1){
						//跨月则设置为月末
						tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
					} else {
						tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
					}

					// 月内日期段内查询
					int tmpDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
					int tmpDateTo = Integer.parseInt(Format.Date8Format.format(tmpClndrStepTo.getTime()));
					while(tmpDateFrom <= tmpDateTo) {
						AlipayClient alipayClient;
						if (getBankConfig().getValueAsBool("isPublicKeyAndCert")){
							alipayClient = new DefaultAlipayClient(getCertAlipayRequest(actItem));
						} else {
							alipayClient = new DefaultAlipayClient(bankFront.serverURL, actItem.appId, actItem.ownKeyStorePath, "json", getCharset(), actItem.oppCertFilePath, "RSA2");
						}

						JSONObject json = new JSONObject();

						json.put("alipay_order_no", p_req7516.actNum);
						json.put("merchant_order_no", p_req7516.actNum);
						json.put("start_time", Format.DateTimeFormat.format(p_req7516.getDateFrom()));
						json.put("end_time", Format.DateTimeFormat.format(p_req7516.getDateTo()));
						json.put("page_no", "1");
						json.put("page_size", "2000");

						AlipayDataBillAccountlogQueryRequest request = new AlipayDataBillAccountlogQueryRequest();
						request.setBizContent(JSON.toJSONString(json));
						AlipayDataBillAccountlogQueryResponse response = alipayClient.execute(request);

						if ("10000".equals(response.getCode())) {
							List list = response.getDetailList();
							for (int i = 0; i < list.size(); i++) {
								RetAtsTransDetail retDetail = new RetAtsTransDetail();
								AccountLogItemResult object = (AccountLogItemResult) list.get(i);
								retDetail.askNumber = object.getAccountLogId();
								if (Integer.parseInt(retDetail.tranAmt) >= 0) {
									retDetail.cdFlag = "2";
								} else {
									retDetail.cdFlag = "1";
								}

								//如果订单金额是正数，则为收入，如果金额为负数，则为支出
								String tranAmt = Format.DecimalAmtFormat.format(Double.parseDouble(object.getTransAmount().trim()));
								if(tranAmt.startsWith("-")) {
									retDetail.tranAmt = tranAmt.replace("-","");
									retDetail.cdFlag = "1";// 支出
								}else {
									retDetail.tranAmt = tranAmt;
									retDetail.cdFlag = "2";// 收款
									retDetail.busType = "代收";
								}
								retDetail.usage = object.getBizDesc();
								retDetail.recAccNum = object.getOtherAccount();
								Date busDateObj = Format.DateTimeFormat.parse(object.getTransDt());
								retDetail.tranDate = Format.Date10Format.format(busDateObj);
								retDetail.tranTime = Format.DateTimeFormat.format(busDateObj);
								retDetail.postTimestamp = Format.DateTime14Format.format(busDateObj);
								retDetail.valueDate = Format.Date10Format.format(busDateObj);
								retDetail.comment = object.getTransMemo();
								retAts.writeRetDetail(retDetail);
							}
						} else {
							tmpRespCode = "-1";
							tmpRespInfo = response.getSubMsg();
						}
						tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
						tmpDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
					}
					tmpCalendarFrom = tmpClndrStepTo;
					tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
					tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
					tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
				}
			} else {
				tmpRespCode = "-1";
				tmpRespInfo = "未找到账号[" + p_req7516.actNum + "]商户配置信息!";
			}
		} catch (Exception e) {
			tmpRespCode = "-1";
			tmpRespInfo = e.getMessage();
			WriteBankLogLn(e);
			e.printStackTrace();
		}
		if(tmpRespCode.equals("-1")){
			retAts = new RetAtsTrans(p_req7516.reqHeader);
			retAts.writeStart();//写返回ATS的统一头部信息
			retAts.writeRespCode(tmpRespCode);
			retAts.writeRespInfo(tmpRespInfo);
		}
		else if(retAts.getWrittenRdCount() == 0){
			retAts.writeRespCode("0");
			retAts.writeRespInfo("交易为空");
		}
		retAts.writeEnd();
		return retAts;
	}

	@Override
	public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
		RetAtsTrans retAts = new RetAtsTrans(p_req7515.reqHeader);
		retAts.writeStart();
		retAts.writeRespCode("0");
		retAts.writeRespInfo("不支持的交易类型:" + p_req7515.reqHeader.transType);
		retAts.writeEnd();
		return retAts;
	}

}
